// http 模块  实现web服务
const http = require('http');
const url = require('url');
const fs = require('fs');
const path = require('path')
// 创建服务 
const server = http.createServer((req,res)=>{
    // console.log(url.parse(req.url,true));
    const {query,pathname} = url.parse(req.url,true);
    // console.log(query);
    // console.log(pathname); /home      /style/home.css
    // 如果访问的是 /home   home.html
    // if(pathname === '/home'){
    //     fs.readFile('client\\views\\home.html','utf-8',(err,data)=>{
    //         if(err){
    //             return console.log(err)
    //         }
    //         res.end(data)
    //     })
    // }

    // 页面views开头
    // http://localhost:8080/views/home.html
    if(/^\/views/.test(pathname)){ ///style/home.css
        ///style/home.css
        const {base} = path.parse(pathname);

        fs.readFile(`client\\views\\${base}`,'utf-8',(err,data)=>{
            if(err){
                fs.readFile('C:\\www\\2303\\day39\\client\\views\\404.html','utf-8',(e,d)=>{
                    res.end(d);
                    
                })
                return 
                
            }
            res.end(data)
        })
        
    }

    // css是样式  约定 css 有个前缀     /style开头  
    // 比如请求 home.css  
    // /style/home.css   http://localhost:8080/style/home.css

    if(/^\/style/.test(pathname)){ ///style/home.css
        ///style/home.css
        const {base} = path.parse(pathname);

        fs.readFile(`client\\css\\${base}`,'utf-8',(err,data)=>{
            if(err){
                fs.readFile('C:\\www\\2303\\day39\\client\\views\\404.html','utf-8',(e,d)=>{
                    res.end(d);
                   
                })
                return
            }
            res.end(data)
        })
        
    }


    if(/^\/js/.test(pathname)){ //   /js/home.js
        // /js/home.js
        const {base} = path.parse(pathname); // home.js

        fs.readFile(`client\\js\\${base}`,'utf-8',(err,data)=>{
            if(err){
                fs.readFile('C:\\www\\2303\\day39\\client\\views\\404.html','utf-8',(e,d)=>{
                    res.end(d);
                   
                })
                return
            }
            res.end(data)
        })
        
    }
})



//启动服务 监听用户访问

server.listen(8080,()=>{
    console.log('css服务启动成功,正在监听8080端口');
})